<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: Repay.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 卡贷升级数据迁移,还款trait
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/2/27 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\ModelTransfers\Traits;

use App\Library\ArrayTools\ArrayTools;
use App\Library\String\Strings;
use App\Models\LoanApply;
use App\Models\RepayRecord;
use App\Models\RepaySummary;
use App\Models\UserGlobal as UserGlobalModel;
use App\ModelTransfers\WsLoans\LoanRepay;
use App\ModelTransfers\WsLoans\LoanVirement;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

Trait Repay
{
    /**
     * Description: 还款数据迁移
     * Author: Gxs
     * @param $loan
     * @return bool
     */
    public static function transfer($loan)
    {
        if (empty($loan)) {
            return true;
        }
        $trans_ids = array_column($loan, 'trans_id');
        $repay_plans = LoanRepay::whereIn('apply_id', $trans_ids)
            ->where('is_valid', 1)
            ->orderBy('plan_repay_time', 'asc')
            ->get();
        $repay_plans = ArrayTools::valuesToKey($repay_plans, 'apply_id');
        $last_apply_id = key(array_slice($repay_plans,-1,1,true)); //最后一个订单id
        //所有放款成功数据(包括历史记录)
        foreach ($loan as $key=>$model) {
            //订单
            $uid = $model->user_id;
            $apply_id = $model->trans_id;
            $bank_card_id = $model->bank_card_id;
            if (!isset($repay_plans[$apply_id])) {
                continue ;
            }
            //获取当前订单号关联的还款计划
            $repay_plan = $repay_plans[$apply_id];
            if (!empty($repay_plan)) {
                if ($apply_id == $last_apply_id) {
                    UserGlobalModel::where('uid', $uid)->update(['global_status' => UserGlobalModel::STATUS_REPAY_INIT]); //还款初始状态
                }
                $period_count = count($repay_plan); //本次订单总期数
                $summary = self::parseLoanApplyData($model, $repay_plan);
                $summary_create = RepaySummary::create($summary);
                $summary_id = $summary_create->id;
                $repay_money = [];
                $repay_month = [];
                $repay_common = [];
                //遍历原卡贷还款计划表
                foreach ($repay_plan as $kk=>$value) {
                    /**
                     * 新流相关
                     */
                    $common_third_record_id = '';
                    $common_trade_no = '';
                    $money_third_repay_id = '';
                    $money_trade_no = '';
                    $money_repayment_money = $common_repayment_money = 0; //原卡贷提前还清手续费确认不存在
                    $record_pay_off = 1; //默认还当期
                    $period = $value->term_no; //当前期
                    //补充资方京东流水号
                    $pay_order_no = '';
                    if (!empty($value->relationLoanVirement->order_id)) {
                        if (!empty($value->relationLoanVirement->relationPayOder)) {
                            $pay_order_no = $value->relationLoanVirement->relationPayOder->channel_order_id;
                        }
                    }
                    if ($value['loan_channel'] == 'LCC201709190010') {
                        //晋商
                        //资方平台状态, 公共平台状态
                        /**
                         * 还款状态
                         */
                        if ($value['status'] >= 3) {
                            //成功
                            $record_status = $month_status = $money_status = $common_status = 4; //本期记录成功状态
                            //公共平台数据 loan_overdue_virement
                            //只有平台的才有减免金额
                            if (empty($value->relationLoanOverdueVirement)) {
                                //平台数据
                                $common_lending_money = 0; //公共利息
                                $common_fines_money = bcsub($value->penalty_amount, $value->employer_penalty_amount, 2); //公共罚息
                                $common_manage_money = $value->actual_service_amount; //公共管理费
                                $common_relief_amount = 0; //公共减免费
                                $common_dicount_amount = $value->dicount_amount; //公共折扣费
                            } else {
                                $common_lending_money = 0; //公共利息
                                $common_fines_money = $value->relationLoanOverdueVirement->penalty_amount; //公共罚息
                                $common_manage_money = $value->relationLoanOverdueVirement->service_amount; //公共管理费
                                $common_relief_amount = $value->relationLoanOverdueVirement->relief_amount; //公共减免费
                                $common_dicount_amount = $value->relationLoanOverdueVirement->dicount_amount; //公共折扣费
                            }

                            //资方平台数据 loan_virement
                            if (empty($value->relationLoanVirement)) {
                                //数据从还款计划表获取
                                $money_lending_money = $value->plan_interest_amount; //资方利息
                                $money_fines_money = $value->employer_penalty_amount; //资方罚息
                                $money_manage_money = 0; //资方管理费
                                $money_dicount_amount = 0; //资方折扣费
                            } else {
                                $money_lending_money = $value->relationLoanVirement->interest_amount;
                                $money_fines_money = $value->relationLoanVirement->penalty_amount;
                                $money_manage_money = $value->relationLoanVirement->service_amount;
                                $money_dicount_amount = $value->relationLoanVirement->discount_amount;
                                $record_pay_off = $value->relationLoanVirement->settle_type == LoanVirement::SETTLE_TYPE_ZERO ? 2 : 1;
                            }
                        } else {
                            //除成功 其他状态条件不明确暂不处理 loan_virement数据不一定存在
                            //置为待处理
                            $record_status = $month_status = $money_status = $common_status = 1; //本期记录状态
                            //晋商需要区分 资金状态 公共状态
                            if (!empty($value->relationLoanVirement) && !empty($value->relationLoanOverdueVirement)) {
                                //都成功
                                $record_status = $money_status = $common_status = 4;
                            } else if (!empty($value->relationLoanVirement)) {
                                //资方成功
                                $money_status = 4;
                            } else if (!empty($value->relationLoanOverdueVirement)) {
                                $common_status = 4;
                            }
                            //数据从还款计划表获取
                            //平台数据
                            $common_lending_money = 0; //公共利息
                            $common_fines_money = bcsub($value->penalty_amount, $value->employer_penalty_amount, 2); //公共罚息
                            $common_manage_money = $value->service_amount; //公共管理费
                            $common_relief_amount = 0; //公共减免费
                            $common_dicount_amount = $value->dicount_amount; //公共折扣费
                            //资方数据
                            $money_lending_money = $value->plan_interest_amount; //资方利息
                            $money_fines_money = $value->employer_penalty_amount; //资方罚息
                            $money_manage_money = 0; //资方管理费
                            $money_dicount_amount = 0; //资方折扣费
                        }
                    } else {
                        //非晋商, 光大 && 龙信
                        $money_dicount_amount = 0;
                        $common_relief_amount = 0;
                        /**
                         * 还款状态
                         */
                        //资方不存在数据 默认为成功状态
                        $month_status = $money_status = 4;
                        //资方不存在数据 默认为0
                        $money_lending_money = $money_fines_money = $money_manage_money = 0;
                        if ($value['status'] >= 3) {
                            //>=3 成功
                            //loan_virement一定存在对应的数据
                            $record_status = $common_status = 4; //本期记录状态
                            /**
                             * 还款数据
                             */
                            if (empty($value->relationLoanVirement)) {
                                //错误数据兼容
                                //取还款计划表数据
                                $common_lending_money = $value->plan_interest_amount; //公共利息
                                $common_fines_money = $value->penalty_amount; //公共罚息
                                $common_manage_money = $value->service_amount; //公共管理费
                                $common_dicount_amount = $value->dicount_amount; //公共折扣费
                            } else {
                                //ws_loan.loan_virement apply_id A022017092776308 存在管理费错误数据
                                $common_lending_money = $value->actual_interest_amount; //实际公共利息
                                $common_fines_money = $value->penalty_amount; //公共罚息
                                $common_manage_money = $value->actual_service_amount; //实际公共管理费
                                $common_dicount_amount = $value->discount_amount; //公共折扣费
                                $record_pay_off = $value->relationLoanVirement->settle_type == LoanVirement::SETTLE_TYPE_ZERO ? 2 : 1;
                            }
                        } else {
                            //除成功 其他状态条件不明确暂不处理 loan_virement数据不一定存在
                            //置为待处理
                            //数据从还款计划表获取
                            $record_status = $common_status = 1; //本期记录状态
                            //取还款计划表数据
                            $common_lending_money = $value->plan_interest_amount; //公共利息
                            $common_fines_money = $value->penalty_amount; //公共罚息
                            $common_manage_money = $value->service_amount; //公共管理费
                            $common_dicount_amount = $value->dicount_amount; //公共折扣费
                        }
                    }

                    //这一订单的是否完成状态回填
                    //根据资方关联表判断本订单是否完成还款
                    //最后一期
                    if ($record_status == 4) {
                        if ($period_count == $period) {
                            $summary_create->period = $period;
                            $summary_create->status = 2;
                            $summary_create->current_repay = 0;
                            $summary_create->save();
                            if ($apply_id == $last_apply_id) {
                                UserGlobalModel::where('uid', $uid)->update(['global_status' => UserGlobalModel::STATUS_REPAY_OVER]); //还款全部结清
                            }
                        } else {
                            $summary_create->period = $period + 1;
                            $summary_create->save();
                        }
                    }

                    //数据填充
                    $repay_date = empty($value->actual_repay_time) ?
                        null : Carbon::createFromTimeString($value->actual_repay_time)->format('Y-m-d'); //真实还款日期
                    //总记录
                    $temp_repay_record = [
                        'uid' => $uid,
                        'summary_id' => $summary_id,
                        'bank_cards_id' => $bank_card_id, //获取原卡贷还款卡号, 如果新平台不存在这张银行卡就用放款的卡
                        'period' => $value['term_no'],
                        'amount' => $value['plan_principal_amount'],
                        'status' => $record_status, //本期还款状态
                        'normal_date' => $value['plan_repay_time'],
                        'repay_date' => $repay_date,
                        'pay_off' => $record_pay_off,
                        'created_at' => $value['create_time'],
                        'updated_at' => $value['update_time'],
                    ];
                    $repay_record_create = RepayRecord::create($temp_repay_record);
                    $record_id = $repay_record_create->id;
                    //月保费 都为0
                    $temp_repay_month = [
                        'uid' => $uid,
                        'summary_id' => $summary_id,
                        'record_id' => $record_id,
                        'bank_cards_id' => $bank_card_id,
                        'period' => $value['term_no'],
                        'status' => $month_status,
                        'created_at' => $value['create_time'],
                        'updated_at' => $value['update_time'],
                    ];
                    $repay_month[] = $temp_repay_month;
                    $temp_repay_money = [
                        'uid' => $uid,
                        'summary_id' => $summary_id,
                        'record_id' => $record_id,
                        'bank_cards_id' => $bank_card_id,
                        'third_repay_id' => $money_third_repay_id,
                        'trade_no' => $money_trade_no,
                        'period' => $value['term_no'],
                        'lending_money' => $money_lending_money,
                        'fines_money' => $money_fines_money,
                        'manage_money' => $money_manage_money,
                        'repayment_money' => $money_repayment_money,
                        'discount_amount' => $money_dicount_amount,
                        'status' => $money_status,
                        'type' => 2,
                        'repay_date' => $repay_date,
                        'created_at' => $value['create_time'],
                        'updated_at' => $value['update_time'],
                    ];
                    $repay_money[] = $temp_repay_money;
                    $temp_repay_common = [
                        'uid' => $uid,
                        'summary_id' => $summary_id,
                        'record_id' => $record_id,
                        'bank_cards_id' => $bank_card_id,
                        'third_record_id' => $common_third_record_id,
                        'trade_no' => $common_trade_no,
                        'period' => $value['term_no'],
                        'lending_money' => $common_lending_money,
                        'fines_money' => $common_fines_money,
                        'manage_money' => $common_manage_money,
                        'repayment_money' => $money_repayment_money,
                        'relief_amount' => $common_relief_amount,
                        'discount_amount' => $common_dicount_amount,
                        'status' => $common_status,
                        'pay_order_no' => $pay_order_no,
                        'created_at' => $value['create_time'],
                        'updated_at' => $value['update_time'],
                    ];
                    $repay_common[] = $temp_repay_common;
                }
                DB::table('repay_record_moneys')->insert($repay_money);
                DB::table('repay_record_months')->insert($repay_month);
                DB::table('repay_record_commons')->insert($repay_common);
            }
        }
        return true;
    }

    /**
     * Description: 解析放款数据
     * Author: Gxs
     * @param LoanApply $model
     * @param array $repay_plan
     * @return array
     */
    public static function parseLoanApplyData($model, $repay_plan)
    {
        $amount = array_sum(array_column($repay_plan, 'plan_principal_amount')); //本次订单总本金
        $period_count = count($repay_plan); //本次订单总期数
        //summary数据组装
        $summary = [
            'uid' => $model->user_id,
            'loan_request_id' => $model->loan_request_id,
            'loan_id' => empty($model->loan_id) ? Strings::createSysLoanId($model->loan_request_id) : $model->loan_id, //从放款获取
            'amount' => $amount, //总金额 还款计划表每期本金相加
            'period_count' => $period_count,
            'period' => 1, //当前期数 需要根据还款计划状态后续变更
            //从放款数据获取
            'rate' => [
                'lending_rate' => $model->lending_rate,
                'insurance_rate' => $model->insurance_rate,
                'month_insurance_rate' => $model->month_insurance_rate,
                'manage_rate' => $model->manage_rate,
                'repayment_rate' => $model->repayment_rate,
                'fines_rate' => $model->fines_rate,
            ],
            'trans_id' => $model->trans_id,
            'loan_channel' => $repay_plan[0]['loan_channel'],
            'data_type' => 2,
            'created_at' => $model->created_at,
            'updated_at' => $model->updated_at,
        ];
        return $summary;
    }

    /**
     * Description: 还款数据迁移数据删除
     * Author: Gxs
     * @param bool $uid
     * @return bool
     */
    public static function removeTransfer($uid = false)
    {
        Log::debug('repay_remove_transfer', ['msg' => 'start']);
        $summary_ids = RepaySummary::when($uid, function ($query) use ($uid) {
                $query->where('uid', $uid);
            })
            ->where('data_type', 2)
            ->pluck('id')->toArray();


        if (!empty($summary_ids)) {
            DB::table('repay_summaries')->whereIn('id', $summary_ids)->delete();
            DB::table('repay_records')->whereIn('summary_id', $summary_ids)->delete();
            DB::table('repay_record_months')->whereIn('summary_id', $summary_ids)->delete();
            DB::table('repay_record_moneys')->whereIn('summary_id', $summary_ids)->delete();
            DB::table('repay_record_commons')->whereIn('summary_id', $summary_ids)->delete();
        }
        Log::debug('repay_remove_transfer', ['msg' => 'end']);
        return true;
    }

}